package com.baohulu.baohulu.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.baohulu.baohulu.MyApplication;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 用于加载 cookie 的拦截器
 */
public class LoadCookiesInterceptor implements Interceptor {
    private static final String TAG = "LoadCookiesInterceptor";

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        String cookie = loadCookie(request.url().host());
        if (!TextUtils.isEmpty(cookie)) {
            Log.d(TAG, "load cookie for url:" + request.url().host() + ",cookie=" + cookie);
            builder.addHeader("Cookie", cookie);
        }
        return chain.proceed(builder.build());
    }

    private String loadCookie(String host) {
        SharedPreferences sp = MyApplication.getAppContext()
                .getSharedPreferences(HttpUtil.COOKIE_PREF, Context.MODE_PRIVATE);
        if (!TextUtils.isEmpty(host) && sp.contains(host)) {
            return sp.getString(host, "");
        }
        return null;
    }
}
